class WebsocketBoot {
  constructor() {
    this.tickTimer = -1;
    this.socket = null;
    this.url = "";
    this.jwt = "";
    this.handlerMap = {};
  }
  loopTick() {
    this.tickTimer = setInterval(() => {
      this.socketSendMessage({
        c: "room",
        m: "ping",
        data: { pos: 0, time: 5 },
      });
    }, 5000);
  }
  socketSendMessage(data) {
    if (this.socket != null) {
      console.log(`socket发送${JSON.stringify(data)}成功`);
      this.socket.send(JSON.stringify(data));
    }
  }
  initSocketEngine(url, jwt) {
    this.url = url;
    this.jwt = jwt;
  }

  startSocket(callback) {
    if (this.socket != null) {
      this.stopSockt();
    }
    if (this.url === "") {
      return;
    }
    if (this.jwt === "") {
      return;
    }
    this.socket = new WebSocket(this.url);
    this.socket.onopen = (event) => {
      console.log("socket打开成功");
      //打开成功，发送登录指令
      this.socketSendMessage({
        c: "room",
        m: "login",
        data: { jwt: this.jwt },
      });
      this.loopTick();
      callback.opened && callback.opened(event);
    };
    this.socket.onmessage = (event) => {
      if (event.data instanceof Blob) {
        const reader = new FileReader();
        reader.readAsText(event.data, "UTF-8");
        reader.onload = (e) => {
          let result = JSON.parse(reader.result);
          console.log("websocked收到", result);
          callback.success && callback.success(result);
          //如果收到登录成功信息，发送进入房间指令
        };
      }
    };
    this.socket.onerror = (event) => {
      console.error("WebSocket报错", event);
      callback.fail && callback.fail(event);
    };
    this.socket.onclose = function (event) {
      console.log("连接关闭");
      callback.closed && callback.closed(event);
    };
  }
  stopSockt() {
    if (this.socket != null) {
      this.socket.close();
    }
    if (this.tickTimer !== -1) {
      clearInterval(this.tickTimer);
      this.tickTimer = -1;
    }
    this.url = "";
    this.jwt = "";
    this.socket = null;
  }
}

//success,fail,opened,closed分别传入回调函数
export const createSocket = ({
  success,
  fail,
  opened,
  closed,
  jwt = JSON.parse(localStorage.getItem("info"))?.jwt,
  lineUrlType='websocket'
}) => {
  //以下为初始化webSocket实例
  let roomSocket = new WebsocketBoot();
  roomSocket.initSocketEngine(`wss://app.xinxin128.com/${lineUrlType}/`, jwt);
  roomSocket.startSocket({
    success,
    fail,
    opened,
    closed,
  });

  return roomSocket;
};

export default WebsocketBoot;
